#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复权限管理系统的数据库结构
"""

import sqlite3
import os

def fix_database_schema():
    """修复数据库表结构"""
    db_path = 'patient_management.db'
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        print("🔧 修复数据库表结构...")
        
        # 检查patients表是否存在id_card和is_visible字段
        cursor.execute("PRAGMA table_info(patients)")
        columns = [column[1] for column in cursor.fetchall()]
        
        # 添加缺失的字段
        if 'id_card' not in columns:
            cursor.execute('ALTER TABLE patients ADD COLUMN id_card TEXT')
            print("✅ 添加 id_card 字段")
        
        if 'is_visible' not in columns:
            cursor.execute('ALTER TABLE patients ADD COLUMN is_visible BOOLEAN DEFAULT 1')
            print("✅ 添加 is_visible 字段")
        
        if 'admission_date' not in columns:
            cursor.execute('ALTER TABLE patients ADD COLUMN admission_date DATE')
            print("✅ 添加 admission_date 字段")
        
        if 'priority' not in columns:
            cursor.execute('ALTER TABLE patients ADD COLUMN priority TEXT DEFAULT "普通"')
            print("✅ 添加 priority 字段")
        
        if 'updated_at' not in columns:
            cursor.execute('ALTER TABLE patients ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP')
            print("✅ 添加 updated_at 字段")
        
        # 确保users表有正确的字段
        cursor.execute("PRAGMA table_info(users)")
        user_columns = [column[1] for column in cursor.fetchall()]
        
        if 'created_at' not in user_columns:
            cursor.execute('ALTER TABLE users ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP')
            print("✅ 添加 users.created_at 字段")
        
        # 提交更改
        conn.commit()
        print("✅ 数据库结构修复完成")
        
        # 验证表结构
        cursor.execute("PRAGMA table_info(patients)")
        patient_columns = [column[1] for column in cursor.fetchall()]
        print(f"📋 patients表字段: {', '.join(patient_columns)}")
        
        conn.close()
        return True
        
    except Exception as e:
        print(f"❌ 数据库修复失败: {e}")
        return False

def insert_test_data():
    """插入测试数据"""
    db_path = 'patient_management.db'
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        print("📊 插入测试数据...")
        
        # 插入测试患者数据
        test_patients = [
            ('张三', '男', 45, '13800138001', '350123198001011234', '2025-08-09', '高血压', '需要定期检查', '李医生', '血压检查', '内科', 3, 'USER', '2025-08-08'),
            ('李四', '女', 38, '13800138002', '350123198501021234', '2025-08-09', '糖尿病', '需要控制饮食', '王医生', '血糖检查', '内科', 3, 'USER', '2025-08-08'),
            ('王五', '男', 52, '13800138003', '350123197001031234', '2025-08-09', '胆结石', '准备手术', '赵医生', 'B超检查', '外科', 4, 'USER', '2025-08-08'),
        ]
        
        for patient_data in test_patients:
            cursor.execute('''
                INSERT OR IGNORE INTO patients 
                (name, gender, age, phone, id_card, examination_date, diagnosis, notes, 
                 reporter, examination_name, department, reported_by, reporter_type, admission_date)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', patient_data)
        
        conn.commit()
        
        # 检查数据
        cursor.execute('SELECT COUNT(*) FROM patients')
        patient_count = cursor.fetchone()[0]
        print(f"✅ 患者数据: {patient_count} 条")
        
        cursor.execute('SELECT COUNT(*) FROM users WHERE is_approved = 1')
        user_count = cursor.fetchone()[0]
        print(f"✅ 已审批用户: {user_count} 个")
        
        conn.close()
        return True
        
    except Exception as e:
        print(f"❌ 测试数据插入失败: {e}")
        return False

def main():
    """主函数"""
    print("🔧 修复权限管理系统数据库...")
    print("=" * 50)
    
    # 修复数据库结构
    if fix_database_schema():
        print("✅ 数据库结构修复成功")
        
        # 插入测试数据
        if insert_test_data():
            print("✅ 测试数据插入成功")
            
            print("\n🎯 修复完成！")
            print("📝 下一步:")
            print("1. 重新运行功能测试: python test_permission_features.py")
            print("2. 验证权限控制和实时传输")
            print("3. 配置跨网络访问")
            print("4. 测试Android客户端")
        else:
            print("⚠️ 测试数据插入失败")
    else:
        print("❌ 数据库结构修复失败")

if __name__ == "__main__":
    main() 